package cn.mntool.backup.server;

import cn.mntool.backup.config.BackupConfig;
import cn.mntool.backup.utils.IdUtils;
import cn.mntool.ftp.core.FtpConfig;
import cn.mntool.ftp.core.SftpManagerSupport;
import org.apache.log4j.Logger;

/**
 * describe: 备份服务
 *
 * @author lianying
 * @date 2019/01/30
 */
public abstract class DbBackupServer {
    private BackupConfig backupConfig;
    private String fileName;
    /**
     * log4j
     */
    private final Logger logger=Logger.getLogger(DbBackupServer.class);

    public DbBackupServer(BackupConfig backupConfig) {
        this.backupConfig = backupConfig;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public BackupConfig getBackupConfig() {
        return backupConfig;
    }

    public void setBackupConfig(BackupConfig backupConfig) {
        this.backupConfig = backupConfig;
    }

    /**
     * 启动备份
     */
    public void start() {
        //生成文件名，并且放入fileName
        setFileName(IdUtils.generate());
        try {
            backup();
            //查看是否开启了ftp备份
            if (getBackupConfig().getOpenFtp()) {
                //根据配置进行不同的上传
                if (getBackupConfig().getSftp()) {
                    logger.info("正在进行sftp备份");
                    uploadSftp();
                } else {
                    logger.info("正在进行ftp备份");
                    uploadFtp();
                }
            }else {
                logger.info("未开启ftp备份");
            }
        } catch (Exception e) {
            error(e);
        }
        close();
    }

    /**
     * 执行备份动作
     *
     * @throws Exception
     */
    public abstract void backup() throws Exception;

    /**
     * 备份失败
     *
     * @param e
     */
    public abstract void error(Exception e);

    /**
     * 上传至sftp服务器
     *
     * @throws Exception
     */
    public void uploadSftp() throws Exception {
        //创建ftpConfig
        String username = getBackupConfig().getFtpUsername();
        String password = getBackupConfig().getFtpPassword();
        String host = getBackupConfig().getFtpHost();
        Integer port = getBackupConfig().getFtpPort();
        FtpConfig ftpConfig = new FtpConfig(username, password, host, port);
        //创建sftp
        SftpManagerSupport sftpManagerSupport = new SftpManagerSupport(ftpConfig);
        sftpManagerSupport.login();
        sftpManagerSupport.upload(getBackupConfig().getDbSavePath() + "/" + getFileName(), getBackupConfig().getFtpSavePath());
        sftpManagerSupport.logOut();
        logger.info("Sftp备份成功");
    }

    /**
     * 上传至ftp
     *
     * @throws Exception
     */
    public abstract void uploadFtp() throws Exception;

    /**
     * 关闭
     */
    public abstract void close();

    /**
     * 生成可用命令
     *
     * @return
     */
    public abstract String formatCommand();
}
